import os
from pywinauto.application import Application
from datetime import datetime
import time
import pywinauto.keyboard as kb
from pywinauto.mouse import click
import argparse
import ctypes

def is_date(s: str, fmt="%m-%d  %H:%M:%S") -> bool:
    try:
        datetime.strptime(s, fmt)
        return True
    except ValueError:
        return False

def main():
    parser = argparse.ArgumentParser(description='微信收藏聊天记录信息读取')
    parser.add_argument('-o',  type=str, default='chat.txt', help='输出文件')
    parser.add_argument('-t',  type=int, default=200,          help='模拟操作后系统响应时间(ms)')
    args = parser.parse_args()
    findWechatFav(args.o,args.t/1000)

def findWechatFav(output='chat.txt',duration=0.2):
    # 连接微信
    # win32api.MessageBox(0, '准备读取微信窗口信息。\r\n\r\n请在微信PC版中选择收藏的聊天记录，点击展示。\r\n\r\n点击“确定”按钮开始读取。读取过程中请勿操作键盘和鼠标！', '提示', win32con.MB_ICONASTERISK | win32con.MB_OK )
    ctypes.windll.user32.MessageBoxW(0, '准备读取微信窗口信息。\r\n\r\n请在微信PC版中选择收藏的聊天记录，点击展示。\r\n\r\n点击“确定”按钮开始读取。读取过程中请勿操作键盘和鼠标！', "提示", 0x00000040)
    try:
        app = Application('uia').connect(title_re='微信', timeout=10,found_index=0)
        main_win = app.window(title_re='微信', class_name='FavRecordWnd') 
        main_win.set_focus() 
    except:
        # win32api.MessageBox(0, '读取微信窗口信息失败，请确认已打开微信收藏的聊天记录窗口！', '错误', win32con.MB_ICONERROR   | win32con.MB_OK)
        ctypes.windll.user32.MessageBoxW(0, '读取微信窗口信息失败，请确认已打开微信收藏的聊天记录窗口！', '错误',0x00000010)
        return
    
    # 获取窗口中心坐标
    rect = main_win.rectangle()
    # center_x = (rect.left + rect.right) // 2
    # 避免点击到中间的图片弹出新窗口
    center_x = rect.left + 50
    center_y = (rect.top + rect.bottom) // 2
    # 模拟点击窗口中央获得焦点
    click(coords=(center_x, center_y))
    time.sleep(duration)

    # 翻页到顶部
    texts = [c.window_text() for c in main_win.descendants(control_type="Text")]
    for i in range(5):
        kb.send_keys("{PGUP}")
        time.sleep(duration)
    texts2 =  [c.window_text() for c in main_win.descendants(control_type="Text")]
    while (not texts==texts2):
        texts = texts2
        for i in range(5):
            kb.send_keys("{PGUP}")
            time.sleep(duration)      
        texts2 =  [c.window_text() for c in main_win.descendants(control_type="Text")] 

    # 翻页并记录
    all_texts = []
    texts = [c.window_text() for c in main_win.descendants(control_type="Text")] 
    # texts.pop(0)
    all_texts += texts
    kb.send_keys("{PGDN}")
    time.sleep(duration)
    texts2 = [c.window_text() for c in main_win.descendants(control_type="Text")] 
    texts2.pop(0)
    while (not texts == texts2):
        all_texts += texts2
        kb.send_keys("{PGDN}")
        time.sleep(duration)
        texts = texts2
        texts2 = [c.window_text() for c in main_win.descendants(control_type="Text")]
        texts2.pop(0)

    # 剔除最后一页读取的重复内容
    repeated = 0
    start = len(all_texts) - 1
    target =  len(all_texts) - 2 * len(texts2) -1
    for i in range(start, target, -1):      
        if is_date(all_texts[i]):
            if all_texts[i] in texts2:
                repeated = i - 1
    if repeated > 0:
        all_texts[repeated:] = []
    all_texts += texts2

    # 输出到文本文件
    need_reline = True
    with open(output, "w", encoding="utf-8") as f:
        for text in all_texts:
            if is_date(text):
                f.write(f"\t\t{text}\n")
                need_reline = True
            else:
                if need_reline:
                    f.write(f"{text}\n\n")
                else:
                    f.write(f"{text}")
                need_reline = False
    
    # 完成提示
    abs_path = os.path.abspath(f.name)
    # win32api.MessageBox(0, "读取微信窗口信息完成，详细内容已写入\r\n"+abs_path, '提示', win32con.MB_ICONASTERISK )
    ctypes.windll.user32.MessageBoxW(0, "读取微信窗口信息完成，详细内容已写入\r\n"+abs_path, '提示',0x00040040)
            
if __name__ == "__main__":
    main()